<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" class="mb-4"  v-show="showSearch">
      <el-form-item label="活动ID">
        <el-input v-model="queryParams.activityId" placeholder="请输入活动ID" clearable />
      </el-form-item>
      <el-form-item label="参数键">
        <el-input v-model="queryParams.paramKey" placeholder="请输入参数键" clearable />
      </el-form-item>
      <el-form-item label="状态" style="width: 150px">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="全部" :value="null" />
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
     <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['admin:menu:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="list" border>
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="活动ID" prop="activityId" align="center" />
      <el-table-column label="参数键" prop="paramKey" align="center" />
      <el-table-column label="参数值" prop="paramValue" align="center" show-overflow-tooltip />
      <el-table-column label="类型" prop="paramType" align="center">
        <template #default="scope">
          {{ paramTypeLabel(scope.row.paramType) }}
        </template>
      </el-table-column>
      <el-table-column label="单位" prop="unit" align="center" />
      <el-table-column label="排序" prop="status" width="80" align="center" />
      <el-table-column
            label="状态"
            align="center"
            width="100"
            v-hasPermi="['admin:user:active']"
          >
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="(val) => handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          
      <el-table-column label="参数说明" prop="remark" align="center" show-overflow-tooltip />
      <el-table-column label="更新时间" prop="updateTime" width="180" align="center" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleEdit(scope.row)"
            v-hasPermi="['admin:menu:update']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['admin:menu:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="open" :title="title" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动标题" prop="activityId">
          <el-input v-model="form.activityId" />
        </el-form-item>
        <el-form-item label="参数键" prop="paramKey">
          <el-input v-model="form.paramKey" />
        </el-form-item>
        <el-form-item label="参数值" prop="paramValue">
          <el-input v-model="form.paramValue" />
        </el-form-item>
        <el-form-item label="参数类型" prop="paramType">
          <el-select v-model="form.paramType" placeholder="请选择类型">
            <el-option label="字符串" :value="0" />
            <el-option label="整数" :value="1" />
            <el-option label="小数" :value="2" />
            <el-option label="布尔" :value="3" />
            <el-option label="JSON" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="参数单位" prop="unit">
          <el-input v-model="form.unit" placeholder="例如：积分 / 元 / 次" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark"> <el-input type="textarea" v-model="form.remark" /> </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import {
  listActivityParam,
  addActivityParam,
  updateActivityParam,
  deleteActivityParam,updateParamStatus
} from "@/api/system/parameterManagement";
import { ElMessage, ElMessageBox } from "element-plus";

// 状态与列表
const loading = ref(false);
const total = ref(0);
const list = ref([]);
const open = ref(false);
const title = ref("");
const formRef = ref(null);
const showSearch = ref(true);

// 分页与搜索参数
const queryParams = reactive({
  page: 1,
  size: 10,
  activityId: "",
  paramKey: "",
  status: null,
});

// 表单数据
const form = reactive({
  id: null,
  activityId: "",
  paramKey: "",
  paramValue: "",
  paramType: 0,
  unit: "",
  sort: 0,
  status: 1,
  remark: "",
});

// 表单校验规则
const rules = {
  activityId: [{ required: true, message: "请输入活动ID", trigger: "blur" }],
  paramKey: [{ required: true, message: "请输入参数键", trigger: "blur" }],
  paramValue: [{ required: true, message: "请输入参数值", trigger: "blur" }],
};

// 类型映射
const paramTypeMap = {
  0: "字符串",
  1: "整数",
  2: "小数",
  3: "布尔",
  4: "JSON",
};
function paramTypeLabel(type) {
  return paramTypeMap[type] || "未知";
}

// 页面初始化
onMounted(() => {
  getList();
});

// 获取列表
async function getList() {
  loading.value = true;
  try {
    const res = await listActivityParam(queryParams);
    if (res.code === 200 && res.data) {
      list.value = res.data.records || [];
      total.value = Number(res.data.total) || 0;
    }
  } finally {
    loading.value = false;
  }
}

// 重置搜索
function resetQuery() {
  queryParams.activityId = "";
  queryParams.paramKey = "";
  queryParams.status = null;
  queryParams.page = 1;
  getList();
}

// 新增
function handleAdd() {
  title.value = "新增活动参数";
  Object.assign(form, {
    id: null,
    activityId: "",
    paramKey: "",
    paramValue: "",
    paramType: 0,
    unit: "",
    sort: 0,
    status: 1,
    remark: "",
  });
  open.value = true;
}

// 编辑
function handleEdit(row) {
  title.value = "编辑活动参数";
  Object.assign(form, JSON.parse(JSON.stringify(row))); // 深拷贝
  open.value = true;
}

// 提交表单
async function submitForm() {
  try {
    await formRef.value.validate();
    const api = form.id ? updateActivityParam : addActivityParam;
    const res = await api(form);
    if (res.code === 200) {
      ElMessage.success("操作成功");
      open.value = false;
      getList();
    }
  } catch (err) {
    console.log("表单验证失败或操作异常", err);
  }
}

// 删除
function handleDelete(row) {
  ElMessageBox.confirm("确认删除该活动参数吗？", "提示", { type: "warning" })
    .then(async () => {
      const res = await deleteActivityParam(row.id);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      }
    })
    .catch(() => {});
}

/** 状态修改  */
/** 参数状态修改  */
async function handleStatusChange(row) {

  const text = row.status === 1 ? "启用" : "禁用";

  try {
    await ElMessageBox.confirm(
      `确认要${text}该参数 "${row.paramKey}" 吗？`,
      "提示",
      { type: "warning" }
    );

    // 调用接口
    const res = await updateParamStatus(row.id, row.status);

    if (res.code === 200) {
      ElMessage.success(`${text}成功`);
    } else {
      throw new Error("接口失败");
    }
  } catch (error) {
    // 回滚状态
    row.status = row.status === 1 ? 0 : 1;
  }
}

</script>
